package com.jams.goodox.activity.qa;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.qa.entity.CourseComment;
import com.jams.goodox.adapter.lfadapter.CommonRecycleViewAdapter;
import com.jams.goodox.adapter.lfadapter.LFRecyclerViewHolder;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.TimeUtils;
import com.jams.goodox.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import me.leefeng.lfrecyclerview.OnItemClickListener;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by HP on 2018/5/17.
 * 添加评论
 */

public class AddCommentActivity extends BaseActivity implements
        OnItemClickListener,LFRecyclerView.LFRecyclerViewListener,
        LFRecyclerView.LFRecyclerViewScrollChange{
    private static final String TAG = AddCommentActivity.class.getSimpleName();

    private int courseId;

//    @Bind(R.id.recyclerView)
//    LFRecyclerView recyclerView;

    private EditText input_box;
    private TextView submit;//

//    private CommonRecycleViewAdapter adapter;
//    private List<CourseComment> dataList = new ArrayList<>();

    /**
     * 输入法管理器
     */
    private InputMethodManager mInputMethodManager;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 1){
                //listComment();
            }
        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.addcomment_activity;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "评论区");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部
        courseId = getIntent().getIntExtra("courseId",-1);

        //初始化输入法
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

//        adapter = new CommonRecycleViewAdapter(recyclerView,dataList,R.layout.addcomment_item) {
//            @Override
//            public void bindConvert(LFRecyclerViewHolder holder, int position, Object item, boolean isScrolling) {
//                CourseComment courseComment = (CourseComment) item;
//                holder.setText(R.id.nickName,courseComment.getNickName());
//                holder.setText(R.id.content,courseComment.getContent());
//                holder.setText(R.id.createTime, TimeUtils.getDateToString(courseComment.getCreateTime()));
//                holder.loadImage(R.id.imageView,courseComment.getImgPath());
//            }
//
//        };

//        View headerView = LayoutInflater.from(this).inflate( R.layout.add_comment_header,null);
//        recyclerView.setHeaderView(headerView);

        input_box = (EditText) findViewById(R.id.input_box);
        input_box.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                input_box.setFocusable(true);//设置输入框可聚集
                input_box.setFocusableInTouchMode(true);//设置触摸聚焦
                input_box.requestFocus();//请求焦点
                input_box.findFocus();//获取焦点
                mInputMethodManager.showSoftInput(input_box, InputMethodManager.SHOW_FORCED);// 显示输入法
            }
        });


        submit = (TextView) findViewById(R.id.submit);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                input_box.setFocusable(false);//设置输入框不可聚焦，即失去焦点和光标
                if (mInputMethodManager.isActive()) {
                    mInputMethodManager.hideSoftInputFromWindow(input_box.getWindowToken(), 0);// 隐藏输入法
                }
                addComment();
            }
        });

        submit.setFocusable(true);
        submit.requestFocus();

//        recyclerView.setFootText("");
//        recyclerView.setLoadMore(false);
//        recyclerView.setRefresh(false);
//        //recyclerView.setNoDateShow();
//        recyclerView.setAutoLoadMore(false);
//        recyclerView.setOnItemClickListener(this);
//        recyclerView.setLFRecyclerViewListener(this);
//        recyclerView.setScrollChangeListener(this);
//        recyclerView.setItemAnimator(new DefaultItemAnimator());
//
//        recyclerView.setAdapter(adapter);

//        handler.sendEmptyMessageDelayed(1,300);
    }


    //添加评论
    private void addComment() {
        if(-1 == courseId){
            ToastUtil.show("课程id为空");
            return;
        }
        if(TextUtils.isEmpty(input_box.getText())){
            ToastUtil.show("请输入您的评论后提交");
            return;
        }

        clearMap();
        StringBuilder pData = new StringBuilder();
        pData.append("courseId:" + courseId)
                .append(",content:" + input_box.getText().toString())
                .append(",memberId:" + SePref.getId());

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).addComment(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);
                    JSONObject jsonObject = new JSONObject(data);
                    if(200 == jsonObject.getInt("code") &&
                            "true".equals(jsonObject.getString("responseData"))){

//                        submit.requestFocus();
//                        input_box.setText("");
                        ToastUtil.show("添加评论成功!");
                        finish();

                        handler.sendEmptyMessageDelayed(1,300);
                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }


    //获取评论列表
//    private void listComment() {
//        clearMap();
//        StringBuilder pData = new StringBuilder();
//        pData.append("courseId:" + courseId)
//                .append(",pageNum:" + 0)
//                .append(",pageSize:" + 20);
//
//        params.put("requestData", "{" + pData.toString() + "}");
//
//        String strEntity = gson.toJson(params);
//        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);
//
//        showLoading();
//        Call<ResponseBody> example = createCallService(LoginService.class).listComment(body);
//
//        example.enqueue(new Callback<ResponseBody>() {
//            @Override
//            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//                misLoading();
//                try {
//                    String data = response.body().string();
//                    Log.d(TAG, "data = " + data);
//                    JSONObject jsonObject = new JSONObject(data);
//                    dataList.clear();
//                    if(200 == jsonObject.getInt("code")){
//                        JSONArray jsonArray = new JSONArray(jsonObject.getString("responseData"));
//                        if(null == jsonArray || jsonArray.length() <= 0){
//                            return;
//                        }
//
//                        for (int i = 0; i < jsonArray.length(); i ++){
//                            JSONObject object = jsonArray.getJSONObject(i);
//                            CourseComment courseComment = new CourseComment();
//                            courseComment.setContent(object.getString("content"));
//                            courseComment.setCreateTime(object.getLong("createTime"));
//                            courseComment.setImgPath(object.getString("imgPath"));
//                            courseComment.setNickName(object.getString("nickName"));
//
//                            dataList.add(courseComment);
//                        }
//
//                        adapter.notifyDataSetChanged();
//
//                    }else {
//                        if(jsonObject.has("error")){
//                            ToastUtil.show("error:" + jsonObject.getString("error") );
//                        }else {
//                            ToastUtil.show("网络异常！" );
//                        }
//                    }
//                } catch (Exception e) {
//                    ToastUtil.show("Exception:" + e.getMessage());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ResponseBody> call, Throwable t) {
//                misLoading();
//                Log.d(TAG,"onFailure = " + t.getMessage());
//            }
//        });
//    }

    @Override
    public void onClick(int position) {

    }

    @Override
    public void onLongClick(int po) {

    }

    @Override
    public void onRecyclerViewScrollChange(View view, int i, int i1) {

    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {

    }
}
